﻿using System;
using System.Linq;
using WebSelfHost.Logic.Sys;
using WebSelfHost.Entity.Sys;
using WebSelfHost.Utility.ResponseModels;
using WebSelfHost.Utility.Core; 
using WebSelfHost.Logic;
using WebSelfHost.Utility.Operator;

using Microsoft.AspNetCore.Mvc;
using WebSelfHost.Entity.WebRequestParms.Sys.User;
using WebSelfHost.Entity.WebRequestParms;
using WebSelfHost.Web.Filters;

#if NETFRAMEWORK
using System.Web.Http;
using OwinSessionMiddleware.WebApi;
#else
using Microsoft.AspNetCore.Http; 
#endif
namespace WebSelfHost.Web.Controllers.Sys
{
    [HiddenApi]
    public class UserController : BaseController
    {
        private SysUserLogic userLogic;
        private SysUserRoleRelationLogic userRoleRelationLogic;
        private SysUserLogOnLogic userLogOnLogic;
        public UserController()
        {
            userLogic = new SysUserLogic();
            userRoleRelationLogic = new SysUserRoleRelationLogic();
            userLogOnLogic = new SysUserLogOnLogic();
        }

        /// <summary>
        /// 用户管理主界面
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("system/user/index"), AuthorizeChecked]
        public ActionResult Index()
        {
            return Html("/Sys/User/Index");
        }

        /// <summary>
        /// 用户管理主界面数据
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        [HttpPost, Route("system/user/index"), AuthorizeChecked]
        public ActionResult Index(UserIndexParms parms)
        {
            int totalCount = 0;
            var pageData = userLogic.GetList(parms.pageIndex, parms.pageSize, parms.keyWord, ref totalCount);
            var result = new LayPadding<SysUser>()
            {
                result = true,
                msg = "success",
                list = pageData,
                count = totalCount//pageData.Count
            };
            return Content(result.ToJson());
        }

        /// <summary>
        /// 新增用户主界面，用户管理主界面新增用户按钮方法
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("system/user/form"), AuthorizeChecked]
        public ActionResult Form()
        {
            return Html("/Sys/User/Form");
        }

        /// <summary>
        /// 新增用户主界面提交信息方法
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, Route("system/user/form"), AuthorizeChecked]
        public ActionResult Form(SysUser model)
        {
            if (model.Id.IsNullOrEmpty())
            {
                DateTime defaultDt = DateTime.Today;
                DateTime.TryParse(model.StrBirthday + " 00:00:00", out defaultDt);
                model.Birthday = defaultDt;
                int row = userLogic.Insert(model, model.password, OperatorProvider.Instance.GetCurrent(Request).Account, model.roleIds.SplitToList().ToArray());
                return row > 0 ? Success() : Error();
            }
            else
            {
                DateTime defaultDt = DateTime.Today;
                DateTime.TryParse(model.StrBirthday + " 00:00:00", out defaultDt);
                model.Birthday = defaultDt;
                //更新用户基本信息。
                int row = userLogic.UpdateAndSetRole(model, OperatorProvider.Instance.GetCurrent(Request).Account, model.roleIds.SplitToList().ToArray());
                //更新用户角色信息。
                return row > 0 ? Success() : Error();
            }
        }


        /// <summary>
        /// 用户详细信息主界面
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("system/user/detail"), AuthorizeChecked]
        public ActionResult Detail()
        {
            return Html("/Sys/User/Detail");
        }

        /// <summary>
        /// 用户详细信息主界面数据，根据userId得到用户信息
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        [HttpPost, Route("system/user/getForm"),LoginChecked]
        public ActionResult GetForm(PrimaryKeyParms parms)
        {
            SysUser entity = userLogic.Get(parms.primaryKey);
            entity.StrBirthday = entity.Birthday.Value.ToString("yyyy-MM-dd");
            entity.RoleId = userRoleRelationLogic.GetList(entity.Id).Select(c => c.RoleId).ToList();
            return Content(entity.ToJson());
        }

        /// <summary>
        /// 用户管理主界面删除用户按钮方法
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        [HttpPost, Route("system/user/delete"), AuthorizeChecked]
        public ActionResult Delete(PrimaryKeyParms parms)
        {
            //多用户删除。
            int row = userLogic.Delete(parms.userIds.SplitToList().ToArray());
            userRoleRelationLogic.Delete(parms.userIds.SplitToList().ToArray());
            userLogOnLogic.Delete(parms.userIds.SplitToList().ToArray());
            return row > 0 ? Success() : Error();
        }

        /// <summary>
        /// 判断当前新增用户名是否存在
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        [HttpPost, Route("system/user/checkAccount"),LoginChecked]
        public ActionResult CheckAccount(PrimaryKeyParms parms)
        {
            var userEntity = userLogic.GetByUserName(parms.primaryKey);
            if (userEntity != null)
            {
                return Error("已存在当前用户名，请重新输入");
            }
            return Success("恭喜您，该用户名可以注册");
        }

        /// <summary>
        /// 用户管理主界面数据
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        [HttpPost, Route("app/system/user/index")]
        public ActionResult AppIndex(UserIndexParms parms)
        {
            int totalCount = 0;
            var pageData = userLogic.GetList(parms.pageIndex, parms.pageSize, parms.keyWord, ref totalCount);
            var result = new LayPadding<SysUser>()
            {
                result = true,
                msg = "success",
                list = pageData,
                count = totalCount//pageData.Count
            };
            return Content(result.ToJson());
        }

        /// <summary>
        /// 新增/修改用户数据提交
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, Route("app/system/user/form")]
        public ActionResult AppForm(SysUser model)
        {
            if (model.Id.IsNullOrEmpty())
            {
                var userEntity = userLogic.GetByUserName(model.Account);
                if (userEntity != null)
                {
                    return Error("已存在当前用户名，请重新输入");
                }
                DateTime defaultDt = DateTime.Today;
                DateTime.TryParse(model.StrBirthday + " 00:00:00", out defaultDt);
                model.Birthday = defaultDt;
                int row = userLogic.AppInsert(model, model.password, model.roleIds.SplitToList().ToArray(), model.CreateUser);
                return row > 0 ? Success() : Error();
            }
            else
            {
                DateTime defaultDt = DateTime.Today;
                DateTime.TryParse(model.StrBirthday + " 00:00:00", out defaultDt);
                model.Birthday = defaultDt;
                //更新用户基本信息。
                int row = userLogic.AppUpdateAndSetRole(model, model.roleIds.SplitToList().ToArray(), model.ModifyUser);
                //更新用户角色信息。
                return row > 0 ? Success() : Error();
            }
        }

        /// <summary>
        /// 通过userId获取用户信息
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        [HttpPost, Route("app/system/user/getForm")]
        public ActionResult AppGetForm(PrimaryKeyParms parms)
        {
            SysUser entity = userLogic.Get(parms.primaryKey);
            entity.StrBirthday = entity.Birthday.Value.ToString("yyyy-MM-dd");
            entity.RoleId = userRoleRelationLogic.GetList(entity.Id).Select(c => c.RoleId).ToList();
            return Content(entity.ToJson());
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        [HttpPost, Route("app/system/user/delete")]
        public ActionResult AppDelete(UserDeleteParms parms)
        {
            //多用户删除。
            int row = userLogic.Delete(parms.userIds.SplitToList().ToArray());
            userRoleRelationLogic.Delete(parms.userIds.SplitToList().ToArray());
            userLogOnLogic.Delete(parms.userIds.SplitToList().ToArray());
            Logger.OperateInfo($"用户{parms.operateUser}删除了用户");
            return row > 0 ? Success() : Error();
        }
    }
}
